# -*- coding: utf-8 -*-
# @author okumura@laurus.co.jp

from gaeo.controller import BaseController
from libs.laurus.action import before_action
from google.appengine.ext.webapp.util import login_required
from model.pigeon import Pigeon
from libs.django.core.paginator import QuerySetPaginator, InvalidPage, EmptyPage


class DraftController(BaseController):
    def before_action(self):
        before_action(self)

    @login_required
    def index(self):
        query = Pigeon.all()
        query.filter('from_user =', self.user)
        query.filter('status =', 'Draft')
        query.order('-post_at')
        paginator = QuerySetPaginator(query, 20)

        if self.params.get('page'):
            page = int(self.params.get('page'))
        else:
            page = 1

        try:
            self.pigeons = paginator.page(page)
        except (EmptyPage, InvalidPage):
            self.pigeons = paginator.page(paginator.num_pages)

    @login_required
    def delete(self):
        if self.params.get('id'):
            pigeon = Pigeon.get_by_id(int(self.params.get('id')))
            if pigeon:
                if pigeon.from_user == self.user:
                    for to in pigeon.pigeontos:
                        to.delete()
                    pigeon.delete()
                    self.session['message'] = u'削除しました'
                    self.session.put()
        self.redirect('/draft')
